package com.muki.corpus;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 原文保存
 * @author ljh_2017
 *
 */
public class CorpusWriting {

	private String root = System.getProperty("user.dir"); 

	/**
	 * 根据url
	 * @param cCID
	 * @throws IOException 
	 */
	public void createFile(String topic,String url,String content) throws IOException {
		Path temp = Paths.get(root,"corpus",topic,url.hashCode()+".txt");
		//获取通道
		FileChannel fc = createOutputChannel(temp);
		ByteBuffer buffer = Charset.forName("utf8").encode(content);
		//buffer.
		System.out.println("+++++++++++++++++++++++++++++");
		int length = 0;
		while((length = fc.write(buffer))!=0) {
			System.out.println("写入长度:"+length);
		}
		//关闭输出通道
		fc.close();
	}

	/**
	 * 创建文件输出通道
	 * @param file
	 * @return
	 */
	@SuppressWarnings("resource")
	private FileChannel createOutputChannel(Path file) {
		FileChannel channel = null;
		try {
			channel = new FileOutputStream(file.toFile()).getChannel();
		} catch (FileNotFoundException e) {
			try {
				Files.createFile(file);
				channel = new FileOutputStream(file.toFile()).getChannel();
			} catch (IOException e1) {
				try {
					Files.createDirectories(file.getParent());
					Files.createFile(file);
					channel = new FileOutputStream(file.toFile()).getChannel();
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			}
		}
		return channel;
	}
}
